using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MSRI.HelperClasses;
using Instedd.Labs.Geo.Library.Sms;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SmsExtension message = SmsManager.GetManager().MessagesManager.GetMessageById(Request.Params["MessageId"]);

            if (message == null)
            {
                SmsClass sms = new SmsClass(Request.Params["Number"], Request.Params["Message"]);
                message = new SmsExtension(sms, null, Request.Params["Message"], Request.Params["SenderName"], SmsManager.GetManager().Configuration.LocalNumber);
            }

            this.LabelSenderName.Text = string.Format("{0} ({1})", message.SenderName, message.Sms.Number);
            this.TextBoxMessage.Text = message.Message;

            Session.Add("Message", message);
        }
    }

    protected void ButtonSend_Click(object sender, EventArgs e)
    {
        SmsExtension message = Session["Message"] as SmsExtension;

        try
        {
            string localNumber = SmsManager.GetManager().Configuration.LocalNumber;
            string localName = SmsManager.GetManager().SenderNameLookupProvider.LookupSenderName(localNumber);
            SmsExtension answer = message.Reply(localName, this.TextBoxAnswer.Text);

            SmsManager.GetManager().Service.SendSms(answer.Sms);
            SmsManager.GetManager().MessagesManager.Save(answer);
            SmsManager.GetManager().GenerateKml();
            SmsManager.GetManager().GenerateGeoRss();
            SmsManager.GetManager().GenerateGeoRssByUser(message.Sms.Number);

            // Move to resources
            this.LabelStatus.Text = string.Format("The message was succesfully sent to {0} ({1})", message.SenderName, message.Sms.Number);
        }
        catch (Exception ex)
        {
            // Move to resources
            this.LabelStatus.Text = string.Format("The message could not be sent. Error: {0}", ex.Message);
            // TODO: Log the exception
        }

    }
}
